<?php
declare(strict_types=1);

namespace Modules\Shop\Service;

use HiCommon\Helper;
use HiCommon\Repository\ActivityRepository;
use HiCommon\Repository\ActivityExtendRepository;
use HiCommon\Repository\ActivityGoodsExtendRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\StoreOrderRepository;

class ActivityService
{


	/**
	 *	获取活动列表
	 *	hinq 2019 10 21
	 *
	 **/
	public function get_list( array $arr_search ){

        $arr_option['where'] = [ 'repairstore_id' => shop_shop_id() ];
        $arr_option['with'] = ['activity_extend','activity_goods_extend'];
		$arr_list = ActivityRepository::get_list( (array) $arr_search ,(array) $arr_option );

		$arr_list->appends($arr_search);//添加链接参数
		$arr_list = list_page_data( $arr_list , $arr_search );

		foreach ($arr_list['data'] as $key => &$value) {
			$value['times'] = date('Y-m-d ', $value['start_time']) . '-' .date('Y-m-d ',$value['over_time']);
			if( $value['status']['status'] == 1 ){
                if( $value['start_time'] > time() ){
                    $value['status']['status_msg'] = '活动未开始';
                }else{
                    $value['status']['status_msg'] = '活动进行中';
                }
            }

			foreach ( $value['activity_extend'] as $k => $val) {
				if( $value['type']['type'] == 1 ){
					$value['activity_extend'][$k] = '满'.  round( $val['price_all'] , 2). '元减' .  round($val['price'] , 2) .'元';
				}else{
					$value['activity_extend'][$k] = '满'. round( $val['price_all'] , 2 ). '元打' .  round($val['price'] , 2 ) . '折';
				}
			}
            $ids = '';
			foreach ( $value['activity_goods_extend'] as $k => $vo ){
			    if( !empty( $vo['goods'] ) ){
                    $ids .= ','.$vo['goods'];
                }
            }
            $count = 0;
            if( !empty( $ids ) ){
                $count = count( explode(',' , trim( $ids , ',') ) );
            }
            $value['goods_count'] = $count;
            unset( $value['activity_goods_extend'] );
		}
		return hello_success('成功',$arr_list);
	}


	/**
	 *	添加活动数据
	 *	hinq 2019 10 21
	 *
	 **/
	public function add_one( array $arr_input ){

		\DB::beginTransaction();
		try { //添加
            //验证提交过来的数据
			$res = self::check_data((array) $arr_input );
            if( $res['state'] == 1 ){
                return $res;
            }
			$data['img'] = $arr_input['img'];
			$data['title'] = $arr_input['title'];
			$data['type'] = $arr_input['type'];
			$data['content'] = $arr_input['content'];
			$times = explode( ' - ' , $arr_input['times'] );
			$data['start_time'] = strtotime( $times[0] );   //开始时间是当天时间的第一秒开始
            $data['over_time'] = strtotime( $times[1] .'23:59:59' );    //结束时间默认是当天的最后一秒
			$data['status'] = 1;
			$data['repairstore_id'] = shop_shop_id();  //  当前登录用户的信息
            $res = ActivityRepository::add_one( (array) $data );
            $temp['activity_id'] = $res->id;
            $res2 = true;
			foreach ( $arr_input['price_all'] as $key => $value) {
			    if( $arr_input['type'] == 1 ){  //满减
                    if( $arr_input['price'][$key] > $value ){     //优惠金额  》 最低消费金额
                        return hello_error('优惠金额设置错误');
                    }
                }
				if( !empty( $value ) ){
					$temp['price_all'] = $value;
					$temp['price'] = $arr_input['price'][$key];
					$res2 = ActivityExtendRepository::add_one( (array) $temp );
				}
			}
			if( $res && $res2 ){
            	\DB::commit();
			}
            return hello_success('添加成功');
        } catch (\Exception $exception) {
        	\DB::rollBack();
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }

	}

	/**
	 *	验证数据有效性
	 *	hinq 2019 10 21
	 *
	 **/
	public function check_data( array $data ){

		if( empty( $data['img'] ) ){
            return hello_error('请上传背景图片');
		}

		if( empty( $data['title'] ) ){
            return hello_error('请填写活动名称');
		}
		if( mb_strlen( $data['title'] ) > 50 ){
            return hello_error('活动名称最多50个字符');
		}
		if( empty( $data['type'] ) ){
            return hello_error('请选择活动类型');
		}
//		if( $data['type'] == 1 && empty( $data['price_all'] ) ){
////            return hello_error('请设置满减信息');
////		}

        if( empty( $data['content'] ) ){
            return hello_error('请填写活动公告');
        }


        if( empty( $data['times'] ) ){
            return hello_error('请设置活动有效期');
        }
        //   当前用户自己的活动  并且在有效的时间范围内
        $arr_where = ['repairstore_id'=> shop_shop_id() ,'status'=>1 ];

        $times = explode(' - ' , $data['times']);
        //不允许添加当天的活动
        if( (int) strtotime( $times[0] ) < time() ){
            return hello_error('活动时间不能小于当前时间');
        }
        if( (int) strtotime( $times[0] ) > (int) strtotime( $times[1] ) ){
            return hello_error('活动的开始时间不能大于结束时间');
        }
        $count = ActivityRepository::get_count_by_where_to_time( (int) strtotime( $times[0] ) , (array) $arr_where , (int)$data['id']  );

        if( $count > 0 ){
            return hello_error('该时间段已有活动，请重新设置活动时间');
        }
        $count = ActivityRepository::get_count_by_where_to_time( (int) strtotime( $times[1] ) , (array) $arr_where , (int)$data['id']  );
        if( $count > 0 ){
            return hello_error('该时间段已有活动，请重新设置活动时间');
        }
        return $data;

	}

	/**
	 *	添加活动的商品信息
	 *	hinq 2019 10 21  3700   920
	 *
	 **/
	public function get_goods_list( int $nId ){

		//获取当前用户的商户id
		$shop_id = shop_shop_id();
		if( empty( $shop_id ) ){
			return [];
		}
		//获取当前活动已设置的模块
		$arr = self::get_goods_list_to_activity( (int) $nId , false );
		$ids = '';
		foreach ($arr as $key => $value) {
			$ids .= $value['goods'] .',';
		}

		$ids = array_unique( explode(',', trim($ids,',') ) );
		$arr_where2['where'] = ['repairstore_id' => $shop_id , 'type' => 1 ,'status' => 1];
		$arr_where2['field'] = ['id','pic_url','name'];
        $ids = [];
		if( count( $ids ) > 0 ){
			$arr_map['field'] = 'id';
			$arr_map['ids'] = $ids;

			$arr_list = GoodsRepository::get_wherenotin_activity_to_goods( (array) $arr_where2 , (array) $arr_map )->toArray();

        	return hello_success('获取成功' , $arr_list );
		}
		//获取所有的订单.
		$arr_list = GoodsRepository::get_where_activity_to_goods( (array) $arr_where2 )->toArray();
        return hello_success('获取成功' , $arr_list );
	}


	/**
	 *  设置活动的商品信息
     *
     **/
	public function goods_list_store( array $arr_input){
		$goods_ids = implode(',',  array_unique( $arr_input['goods_list'] ) );		

        //获取当前活动信息
        $arr_option['field'] = ['id','start_time','over_time'];
        $activity_info = ActivityRepository::get_one( (int) $arr_input['id'] , (array) $arr_option );
        if( empty( $activity_info->first() ) ){
            return hello_error('参数错误');
        }
        $activity_info = $activity_info->toarray();

        if( $activity_info['start_time'] < time() ){
            //获取当前活动是否添加过商品
            $count = ActivityGoodsExtendRepository::get_count_by_where( ['activity_id'=>$activity_info['id']]);
            if( $count > 0 ){   //进行中的活动 但是没有添加商品  允许添加商品
                return hello_error('参与活动期间的活动不支持修改内容');
            }
        }

		$data['activity_id'] = $arr_input['id'];
		$data['name'] = $arr_input['name'];
		$data['goods'] = $goods_ids;
		$res = ActivityGoodsExtendRepository::add_one( (array) $data );
		//将设置的商品设置为活动商品
//		GoodsRepository::change_status((array) array_unique( $arr_input['goods_list'] ) , (array) ['type'=>3]);
		if (empty($res)) {
            return hello_error('添加失败');
        }
        return hello_success('添加成功');
	}




	public function get_goods_list_to_activity( int $nId , bool $is_goods = true ){

		try{
			$arr_where['where'] = ['activity_id'=>$nId];
			$arr_where['order'] = ['key'=>'created_at','value'=>'asc'];
			$arr_where['field'] = ['id','activity_id','name','goods'];
			$arr_list = ActivityGoodsExtendRepository::get_all( (array) $arr_where )->toArray();
			if( count( $arr_list ) > 0 && $is_goods ){
				$map['field'] = 'id';
				$arr_option['field'] = ['id','pic_url','name'];
				foreach ($arr_list as $key => $value) {
					$ids = explode(',', $value['goods'] );
					$map['ids'] = $ids;
					$goods_info = GoodsRepository::get_wherein_activity_to_goods( (array)$arr_option , (array) $map )->toArray();
					$arr_list[$key]['goods_info'] = $goods_info;
				}
			}
			return $arr_list;
 		} catch (\Exception $exception) {
        	\DB::rollBack();
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}



	/**
	 *	强制禁用活动（不可恢复到正常状态）
	 *	hinq 2019 10 23
	 *	
	 **/
	public function change_status( int $nId ){
		try{

			if( empty( $nId ) ){
            	return hello_error('参数错误');
			}
			//获取当前活动的状态
			$arr_option['field'] = ['id','status'];
			$activity_info = ActivityRepository::get_one( (int) $nId , (array) $arr_option )->toArray();

			if( count( $activity_info ) == 0 ){
            	return hello_error('参数错误');
			}
			if( $activity_info['status']['status'] != 1 ){
            	return hello_error('该活动已禁用');
			}
			$data['status'] = 3;
			$data['id'] = $nId;
			$res = ActivityRepository::edit_one( $data );
			if (empty($res)) {
            	return hello_error('禁用失败');
	        }
	        return hello_success('禁用成功');
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}


	/**
	 *	删除活动的商品模块
	 *	hinq 2019 10 23
	 *
	 **/
	public function del_one( $arr_input ){
		try{

			if( empty( $arr_input ) ){
				return hello_error('参数错误');
			}
            //获取当前活动信息
            $arr_option['field'] = ['id','start_time','over_time'];
            $activity_info = ActivityRepository::get_one( (int) $arr_input['activity_id'] , (array) $arr_option );

            if( empty( $activity_info->first() ) ){
                return hello_error('参数错误');
            }
            $activity_info = $activity_info->toarray();
            if( $activity_info['start_time'] < time() ){
                return hello_error('活动进行中，禁止删除商品信息');
            }

			$res = ActivityGoodsExtendRepository::delete_one( (int) $arr_input['id'] );
			if (empty($res)) {
            	return hello_error('删除失败');
	        }
	        return hello_success('删除成功');
		} catch (\Exception $exception) {
        	\DB::rollBack();
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}
	
	/**
	 *	详细信息获取指定的活动
	 *	hinq 2019 10 25
	 *
	 **/
	public function get_one( int $nId ){
		try {
			if( empty( $nId ) ){
				return ['state'=>1,'msg'=>''];
			}
			//获取指定的活动数据
			$arr_option['field'] = ['id','img','title','type','content','start_time','over_time','created_at','status','repairstore_id'];
			$arr_option['with'] = ['activity_extend'];
			$arr_list = ActivityRepository::get_one( (int) $nId , (array) $arr_option )->toArray();

			if( count( $arr_list ) < 1 ){
				return [];
			}
			if( $arr_list['start_time'] > time() ){   //活动开始时间大于当前时间 
				$arr_list['msg'] = '未开始';
			}
			if( $arr_list['start_time'] < time()  && $arr_list['over_time'] > time() ){   //活动开始时间大于当前时间 小于结束时间
				$arr_list['msg'] = '进行中';
			}
			if(  $arr_list['over_time'] < time() ){   //活动结束时间小于当前时间 
				$arr_list['msg'] = '已结束';
			}
			$arr_list['times'] = date('Y-m-d H:is', $arr_list['start_time'] ) . ' - ' . date('Y-m-d H:is', $arr_list['over_time'] );
			//统计当前活动订单信息
			$arr_options = ['order_type'=>2,'activity_id'=>$nId,'pay_status'=>2];
			$arr_order = StoreOrderRepository::get_user_to_order_count( (array) $arr_options)->toArray();
			//统计当前活动参与的人数（同一用户不管下单多少都只算一次）
			$participant_num = StoreOrderRepository::count_participant_activity_user( (array) $arr_options);
			$data = [
				'day' => (string) round( ($arr_list['over_time'] - $arr_list['start_time']) / 3600 /24 ),   //活动持续的天数
				'order_total' => $arr_order[0]['total'],      //订单总数
				'profit' => (string) floatval( $arr_order[0]['pay_amount'] ),      //盈利金额
				'user_num' => $participant_num,      //参与人数
			];


			$temp = [
				'info' => $arr_list,
				'data' => $data,
			];

			return $temp;
		} catch ( \Exception $exception ) {
			return ['state'=>1,'msg'=>$exception->getMessage()];
		}
	}


	/**
	 *	活动详情获取与活动相关的订单
	 *	hinq 2019 10 26
	 *
	 **/
	public function get_order_list( int $nId ){
		try {

			$arr_option['where'] = ['order_type'=>2,'activity_id'=>$nId ,'pay_status'=>2 ];
			$arr_option['with'] = ['getUser'];
			$arr_option['field'] = ['id','order_no','pay_status','order_amount','pay_time','pay_amount','coupon_price','status','user_id','pay_type','created_at'];
			$arr_list = StoreOrderRepository::get_list( (array) $arr_option )->toArray();

			foreach ($arr_list['data'] as $key => &$value) {
                $value['user_name'] = $value['get_user']['nickname'];
                $value['phone'] = $value['get_user']['phone'];
                $value['pay_status'] = $value['status'] == 1 ? '已支付': '未支付';
                $value['pay_type'] = $value['pay_type'] == 1 ? '微信': '支付宝';
				$value['status_msg'] = $value['status']['name'];
				unset( $value['get_user'] );
			}
			return ['code'=>0,'msg'=>'','data'=>$arr_list['data'],'count'=>$arr_list['total']];
		} catch (\Exception $exception ) {
			return ['state'=>1,'msg'=>$exception->getMessage()];
		}
	}
}